<template>
  <div class="container">
    <header class="header">
      
      <el-page-header>
        <template #breadcrumb>
          <el-breadcrumb separator="||">
            <el-breadcrumb-item :to="{ path: '/' }">
              首页
            </el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/category' }">分类</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
          </el-breadcrumb>
        </template>
        <template #title>
          <span @click="router.go(-1);">返回</span>
        </template>
        <template #content>
          <span class="text-large font-600 mr-3"> 图书详情 </span>
        </template>
      </el-page-header>

    </header>

    <div class="detail-content">
      <div class="content-box">
        <!-- 图片区域 -->
        <div class="content-l">
          <img :src="bookDetails.photo" >
        </div>
        <!-- 信息展示区域 -->
        <div class="show-info">

          <h3>{{ bookDetails.book_name }}</h3>
          <span class="common-size">作者：{{ bookDetails.author }} | 格式：电子书</span>
          <div class="df">
            <span class="common-size">星级</span>
            <el-rate v-model="starRate" disabled />
          </div>
          <el-divider />
          <div class="df">
            <span>出版社：</span>
            <span>{{ bookDetails.publisher  }}</span>
          </div>
          <div class="df">
            <span>ISBN：</span>
            <span>{{ bookDetails.isbn  }}</span>
          </div>
          <div class="df">
            <span>分类：</span>
            <span>{{ bookDetails.category_name  }}</span>
          </div>
          <div class="df">
            <span>是否上架(可购买)：</span>
            <span>{{ bookDetails.statuss == 1? '已上架' : '未上架' }}</span>
          </div>
          <div class="df">
            <span>单价：</span>
            <span>{{ bookDetails.price  }}</span>
          </div>
          <div class="df">
            <span>销量：</span>
            <span>{{ bookDetails.sales  }}</span>
          </div>
          <div class="df">
            <span>库存：</span>
            <span>{{ bookDetails.stock  }}</span>
          </div>
          <div>
            <span>图书简介：</span>
            <p class="common-size intro">{{ bookDetails.briefIntro  }}</p>
          </div>
          <el-divider />
          <div>
            <span>推荐类似：</span>
            <ul class="similarList" v-if="similarBookList.length != 0">
              <li 
                v-for="item in similarBookList" 
                :key="item.book_id"
                @click="goDetailsItem(item)"
              >
                <el-card :body-style="{ padding: '0px' }">
                  <img
                    :src="item.photo"
                    class="image"
                  />
                  <div class="card-bottom">
                    <span class="name">{{ item.book_name }}</span>
                    <span class="intro">{{ item.briefIntro }}</span>
                  </div>
                </el-card>
              </li>
            </ul>

            <el-empty v-else :image-size="200" />

          </div>
        </div>
        <!-- 点击加入购物车卡片 -->
        <div class="content-r">
          <div class="card">

            <div>
              <div class="df">
                <span>电子书原定价：</span>
                <span class="oldPrice">￥{{ bookDetails.price + 99 }}</span>
              </div>
              <div class="df">
                <span>现此电子书价格：</span>
                <span class="newPrice">￥{{ bookDetails.price }}</span>
              </div>
            </div>
            <div class="df" v-if="bookDetails.statuss == 1">
              <button class="addBtn" @click="addToCart">加入购物车</button>
            </div>
            <div v-else>
              <span>
                此件商品暂未上架，咱不可加入购物车购买...
              </span>
            </div>

          </div>
        </div>
      </div>
    </div>

    <Footer :bgColor="'gray'"></Footer>
  </div>
</template>

<script setup>
// components
import Footer from '../../components/common/Footer.vue';

// router
import { onBeforeMount, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';

// api
import bookModelApi from '@/request/api/book.js';
import cartModelApi from '@/request/api/cart.js'

import { ElMessage, ElMessageBox } from 'element-plus'

// utils
import { getRandomItems } from '@/utils/arrayUtil.js'

const store = useStore();

// 路由对象
const route = useRoute();
const router = useRouter();

// 对应的图书信息
const bookDetails = ref({})

// 推荐类似图书
let similarBookList = ref([]);

watchEffect(() => {

  // 根据 id 获取对应图书信息
  initInfo();

  const loadingInstance = ElLoading.service({ fullscreen: true, text: '亲,数据加载中,请稍等...' });
  setTimeout(() => {
    loadingInstance.close()
  },600)

  // 推荐类似 从相同分类中找5条
  // 根据分类 category_id 获取其他所有同类型图书数据
  setTimeout(() => {
    bookModelApi.getAllBookByCategoryIdApi({
      category_id: bookDetails.value.category_id
    }).then(res => {
      // 先把当前的书本屏蔽掉再进行推荐
      const recList = res.data.filter(item => item.book_id != bookDetails.value.book_id)
      // 再找出3本推荐的书
      similarBookList.value = getRandomItems( recList, 3 );
      console.log('similarBookList.value', similarBookList.value)
    })
  },500)
 
  
})

// 根据 id 获取对应图书信息
function initInfo(){
  bookModelApi.getBookByIdApi({
    book_id: route.query.book_id
  }).then(res => {
    if(res.code != 200) return;
    bookDetails.value = res.data;

    bookDetails.value.category_name = store.state.book.cateGoryList.filter(item => item['category_id'] == bookDetails.value.category_id)[0].category_name;

  })
}


// 点击推荐又去到详情页面
const goDetailsItem = item => {
  router.push({
    path: `/details`,
    // 显式传参
    query: { 
      book_id: item.book_id
    }
  })
}

// 星级评分
const starRate = ref(4)

// 加入购物车
const addToCart = () => {
  ElMessageBox.confirm(
    '确定将此件商品加入购物车吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let params = {
        user_name: store.state.user.userInfo.username,
        bookId: bookDetails.value.book_id,
        un_price: bookDetails.value.price
      }
      cartModelApi.addBookToCartApi( params ).then(res => {
        if(res.code == '401'){
          ElMessage({
            showClose: true,
            type: 'error',
            message: `${res.msg},请先登录`,
          })
        }else{
          ElMessage({
            showClose: true,
            type: 'success',
            message: `${res.msg},可前往我的购物车中查看`,
          })
        }
        
      })
      
    })
    .catch(() => {
      ElMessage({
        showClose: true,
        type: 'info',
        message: '取消操作',
      })
    })
}



</script>

<style lang='less' scoped>
.container{
  height: 100%;
  width: 100%;
}

.header{
  height: 80px;
  z-index: 999;
  background: #efefef;
  .el-page-header{
    height: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: row-reverse;
    align-items: center;
    padding: 0 10px;
    span{
      font-size: 18px;
    }
  }
}
.detail-content{
  width: 100%;
  .content-box{
    width: 85%;
    box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px, rgba(0, 0, 0, 0.22) 0px 15px 12px;
    margin: 0 auto;
    padding: 10px;
    display: flex;
    .content-l{
      box-sizing: border-box;
      width: 300px;
      height: 400px;
      flex: 1;
      img{
        width: 100%;
        height: 100%;
      }
    }
    .show-info{
      border-left: 1px solid #000;
      margin-left: 20px;
      padding: 10px;
      flex: 3;
      .common-size{
        font-size: 14px;
        &.intro{
          margin-top: 15px;
        }
      }
      .df{
        margin: 10px 0;
        display: flex;
        align-items: center;
      }
      .similarList{
        margin-top: 20px;
        display: flex;
        justify-content: space-around;
        li{
          transition: 0.3s;
          cursor: pointer;
          .el-card{
            width: 220px;
            height: 350px;
            img {
              width: 100%;
              height: 250px;
            }
          }
          .card-bottom{
            display: flex;
            flex-direction: column;
            padding: 14px;
            .name{
              color: yellowgreen;
            }
            .intro{
              font-size: 13px;
              overflow: hidden;
              text-overflow: ellipsis; /* 文字溢出省略号 */
              white-space: nowrap; /* 不换行 */
            }
          }
          &:hover{
            transform: translateY(-10px);
          }
        }
      }
    }
    .content-r{
      flex: 1;
      display: flex;
      align-items: center;
      .card{
        width: 100%;
        height: 250px;
        box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
        padding: 20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .df{
          display: flex;
          margin: 10px 0;
          .oldPrice{
            text-decoration: line-through;
          }
          .newPrice{
            color: orange;
          }
          .addBtn{
            width: 100%;
            padding: 5px;
            border: none;
            border-radius: 20px;
            background: orange;
            cursor: pointer;
            transition: 0.25s;
            &:hover{
              background: rgb(236, 179, 75);
            }
          }
        }
      }
    }
  }
}
</style>